/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import ferramentas.CFG;
import ferramentas.Query;
import ferramentas.certificado.GeradorCertificadoPDF;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pessoal.Certificado;
import pessoal.Inscrito;

/**
 *
 * @author ciar
 */
public class downloadCertificado extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {

        response.setContentType("application/download");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            if (request.getParameter("inscricao") != null) {
                String numeroInscricao = request.getParameter("inscricao");

                Query q = new Query();
                Certificado certificado = q.getCertificado(Integer.parseInt(numeroInscricao));

                String root = getServletContext().getRealPath("/");
                // TESTE
                //root = "/home/ciar/bridge_tmp/ROOT";

                String localCertificadoPDF = root.substring(0, root.lastIndexOf(getServletContext().getContextPath().replace("/", System.getProperty("file.separator"))))
                        + System.getProperty("file.separator") + CFG.DIRETORIO_ARQUIVOS
                        + System.getProperty("file.separator") + CFG.DIRETORIO_CERTIFICADOS;

                GeradorCertificadoPDF geradorCertificado = new GeradorCertificadoPDF(certificado, localCertificadoPDF);

                geradorCertificado.gerarPDF();

                File arquivoPDF = geradorCertificado.getCertificado();

                int length = (int) arquivoPDF.length();
                ServletOutputStream op = response.getOutputStream();
                response.setContentLength((int) length);
                response.setHeader("Content-Disposition", "attachment; filename=\"" + geradorCertificado.getNomeArquivoPDF() + "\"");
                byte[] bbuf = new byte[32767];
                DataInputStream in = new DataInputStream(new FileInputStream(arquivoPDF));

                while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                    op.write(bbuf, 0, length);
                }

                in.close();
                op.flush();
            } else {
                if (request.getParameter("curso") != null) {
                    int numeroCurso = Integer.parseInt(request.getParameter("curso"));

                    Query q = new Query();
                    ArrayList<Integer> aprovados = q.getInscricoesAprovados(numeroCurso);

                    String root = getServletContext().getRealPath("/");
                    //root = "C:\\teste";

                    int last = root.lastIndexOf(getServletContext().getContextPath().replace("/", System.getProperty("file.separator"))) > 0 ? root.lastIndexOf(getServletContext().getContextPath().replace("/", System.getProperty("file.separator"))) : root.length();
                    String localCertificadoPDF = root.substring(0, last)
                            + System.getProperty("file.separator") + CFG.DIRETORIO_ARQUIVOS
                            + System.getProperty("file.separator") + CFG.DIRETORIO_CERTIFICADOS;

                    ArrayList<File> arquivos = new ArrayList<File>();
                    for (Integer aluno : aprovados) {
                        Certificado certificado = q.getCertificado(aluno.intValue());

                        GeradorCertificadoPDF geradorCertificado = new GeradorCertificadoPDF(certificado, localCertificadoPDF);

                        geradorCertificado.gerarPDF();

                        File arquivoPDF = geradorCertificado.getCertificado();
                        arquivos.add(arquivoPDF);
                    }
                    if (arquivos.size() > 0) {
                        byte[] zip = zipFiles(arquivos);

                        //
                        // Sends the response back to the user / browser. The
                        // content for zip file type is "application/zip". We
                        // also set the content disposition as attachment for
                        // the browser to show a dialog that will let user 
                        // choose what action will he do to the sent content.
                        //
                        ServletOutputStream sos = response.getOutputStream();
                        response.setContentType("application/zip");
                        response.setHeader("Content-Disposition", "attachment; filename=\"certificados.zip\"");

                        sos.write(zip);
                        sos.flush();
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        } finally {
        }
    }

    /**
     * Compress the given directory with all its files.
     */
    private byte[] zipFiles(List<File> arquivos) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        byte bytes[] = new byte[2048];

        for (File arquivo : arquivos) {
            FileInputStream fis = new FileInputStream(arquivo);
            BufferedInputStream bis = new BufferedInputStream(fis);

            zos.putNextEntry(new ZipEntry(arquivo.getName()));

            int bytesRead;
            while ((bytesRead = bis.read(bytes)) != -1) {
                zos.write(bytes, 0, bytesRead);
            }
            zos.closeEntry();
            bis.close();
            fis.close();
        }
        zos.flush();
        baos.flush();
        zos.close();
        baos.close();

        return baos.toByteArray();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(downloadCertificado.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(downloadCertificado.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
